import { loginAPI, getInfoAPI, getUserAvatarAPI } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  /**
   * @description 登录功能
   * @param {*} param0 
   * @param {mobile,password} userInfo 
   * @returns Promise
   */
  // loginActions({ commit }, userInfo) {
  //   const { mobile, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     loginAPI({ mobile: mobile.trim(), password: password }).then(res => {
  //       commit('SET_TOKEN', res.data)
  //       setToken(res.data)
  //       resolve(res.message)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  loginActions({ commit }, userInfo) {
    const { mobile, password } = userInfo
    return  loginAPI({ mobile: mobile.trim(), password: password }).then(res => {
        commit('SET_TOKEN', res.data)
        setToken(res.data)
        return res.message
      })
    
  },

  /**
   * @description 获取用户基本信息
   * @param {*} param0 
   * @returns Promise
   */
  async getInfoActions({ commit }) {
  const { data: userObj } = await getInfoAPI()
    const { data: avatarObj } = await getUserAvatarAPI(userObj.userId)
    commit('SET_USER_INFO', { ...userObj, ...avatarObj })
   return userObj.roles
  },

  /**
   * @description 退出功能
   * @param {*} param0 
   * @returns Promise
   */
  logoutActions({ commit }) {
    resetRouter()
    removeToken()
    commit('RESET_STATE')

  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

